package com.cuiweiyou.uiautomator20;

import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Rect;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.widget.EditText;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.List;

/**
 * www.gaohaiyan.com
 */
@RunWith(AndroidJUnit4.class)
public class TestAccepting {
    private static final String TAG = "ard";
    private static UiDevice device;
    private static Context context;
    private static String nameSplitFlag = "<<>>";

    @BeforeClass // 此方法须静态
    public static void beforeClass() throws RemoteException {
        UtilLogs.saveLog("1.BeforeClass");

        UtilFile.initSourcePath(); // accepting

        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        context = instrumentation.getTargetContext().getApplicationContext();

        device = UiDevice.getInstance(instrumentation);

        if (!device.isScreenOn()) {
            device.wakeUp();
        }

        TestUtilCtrl.requestPermission(device);
        UtilSQLite.getInstance(context);
    }

    @Before
    public void before() {
        UtilLogs.saveLog("2.Before");

        UtilLogs.saveLog(" ");
        UtilLogs.saveLog(" ");
        UtilLogs.saveLog(" ");
        UtilLogs.saveLog("++++++++ 开始自动通过陌生人请求 ++++++++");
    }

    @After
    public void after() {
        UtilLogs.saveLog("-2.After");
    }

    @AfterClass // 此方法须静态
    public static void afterClass() {
        UtilLogs.saveLog("-1.AfterClass");
    }

    /**
     * 通过陌生好友的主动请求
     */
    @Test
    public void testAccepting() {
        TestUtilCtrl.launcherWechatApp(device, "通过陌生好友的请求");
        TestUtilCtrl.switchTab(device, "通讯录");
        TestUtilCtrl.swipeListViewToTopItem(device); // accepting test
        scrollGotoShowNewFriendBtn(); // 通过陌生人请求

        // nextAty，进入"新的朋友   添加朋友"界面
        // 如果有加好友的主动请求会出现在列表中，关键字"接受"
        // 已经通过的显示"已添加"

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        TestUtilCtrl.showCurrentActivity(device, "是否为'新的朋友-添加朋友'"); // 聊天页

        UiScrollable listViewObject = new UiScrollable(new UiSelector().className("android.widget.ListView"));
        scrollAcceptListView(listViewObject);  // 启动通过陌生好友的主动请求

        for (int i = 0; i < 6; i++) {
            device.pressBack();
        }
    }

    // 划动列表 通过到陌生人的好友请求
    private void scrollAcceptListView(UiScrollable listViewObject) {
        TestUtilCtrl.swipeListViewToBottomItem(device);

        listViewObject.setMaxSearchSwipes(100);
        listViewObject.setAsVerticalList();
        boolean hasStartChatObject = false;
        String targetString = "接受";  // id是com.tencent.mm:id/bmh，android.widget.Button
        UiObject targetObject = device.findObject(new UiSelector().textContains(targetString));
        try {
            hasStartChatObject = listViewObject.scrollIntoView(targetObject); // 这个总是从listview最底部向上滚动查找，每找到一个匹配项就停止
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        }
        listViewObject.waitForExists(5000);
        UtilLogs.saveLog("滚动查找，是否新通过的朋友item：" + hasStartChatObject);

        if (hasStartChatObject) {
            try {
                // targetObject.click();
                Rect bounds = targetObject.getBounds();
                int clickY = bounds.centerY();
                int clickX = device.getDisplayWidth() / 2;
                device.click(clickX, clickY);
                UtilLogs.saveLog("点击了'接受'按钮：x=" + clickX + "，y=" + clickY);
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
                scrollAcceptListView(listViewObject);
            }

            // nextAty，进入详细资料界面

            device.wait(Until.hasObject(By.textContains("通过验证")), 5000);

            TestUtilCtrl.showCurrentActivity(device, "是否为'详细资料'");

            String[] friendDetails = getFriendDetails(0); // 陌生人主动加好友
            String wxid = friendDetails[0];
            String notename = friendDetails[1];
            String nickname = friendDetails[2];

            UiObject2 acceptObject = device.findObject(By.textContains("通过验证"));
            acceptObject.click();
            UtilLogs.saveLog("点击了 通过验证");

            // nextAty，进入朋友验证界面

            device.wait(Until.hasObject(By.clazz(EditText.class)), 5000);

            TestUtilCtrl.showCurrentActivity(device, "是否为'朋友验证'");

            List<UiObject2> editTextList = device.findObjects(By.clazz(EditText.class));
            for (int i = 0; i < editTextList.size(); i++) {
                UiObject2 edit = editTextList.get(i);
                String editClassName = edit.getClassName(); // android.widget.EditText
                edit.setText(""); // 清空默认填入的称呼，使关键字词hint显示
            }

            device.wait(Until.hasObject(By.textContains("完成")), 5000);

            UiObject2 finishObject = device.findObject(By.text("完成"));
            finishObject.click();
            UtilLogs.saveLog("点击了-朋友验证，完成");

            // backAty，自动 回到详细资料界面

            device.wait(Until.hasObject(By.textContains("发消息")), 5000);

            TestUtilCtrl.showCurrentActivity(device, "是否为'详细资料'");

            UiObject2 sendMsgObject = device.findObject(By.text("发消息"));
            sendMsgObject.click();
            UtilLogs.saveLog("点击了-发消息");

            // nextAty，自动进入此好友的对话聊天页面

            device.wait(Until.hasObject(By.res("com.tencent.mm", "j7")), 5000);

            TestUtilCtrl.showCurrentActivity(device, "是否为'朋友聊天'");

            String phone = "";
            UiObject2 titleObject = device.findObject(By.res("com.tencent.mm", "j7"));
            String title = titleObject.getText();
            if (title.contains(nameSplitFlag)) {
                String[] split = title.split(nameSplitFlag);
                phone = split[0];
                notename = split[1];
            } else {
                notename = title;
            }

            String[] friendAvatar = getFriendAvatar(notename);// 陌生人的主动好友请求，查找好友的头像，进行点击，用以获取微信号等
            wxid = friendAvatar[0];
            notename = friendAvatar[1];
            nickname = friendAvatar[2];

            UtilSQLite.getInstance(context).insertFriend("", wxid, notename, nickname, "reactive"); // 主动请求加我的人

            // 这里暂不处理，统一到聊天流程

            device.pressBack(); // 回到首页

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            TestUtilCtrl.showCurrentActivity(device, "是否为'首页'");

            testAccepting(); // 下一次查找
        } else {
            TestUtilCtrl.swipeListViewToBottomItem(device);
            TestUtilCtrl.swipeListViewToTopItem(device); // accepting

            UtilLogs.saveLog("划动屏幕-通过新朋友的主动请求-并问好-完毕");
        }
    }

    /**
     * 好友到详细信息界面
     *
     * @param flag 0-主动请求加人到朋友，1-已经是朋友关系的，2-好友查找
     * @return 返回资料数组：0-微信号，1-备注名，2-昵称
     */
    private String[] getFriendDetails(int flag) {
        UtilLogs.saveLog("查看详细资料，来源页面：" + flag);

        String[] result = new String[3];
        result[0] = "";
        result[1] = "";
        result[2] = "";

        device.wait(Until.hasObject(By.textContains("详细资料")), 5000);

        Boolean hasWxidObject = device.wait(Until.hasObject(By.textContains("微信号:")), 5000);
        if (hasWxidObject) {
            UiObject object = device.findObject(new UiSelector().textContains("微信号:"));
            String wxid = null;
            try {
                wxid = object.getText().replace("微信号:", "");
                result[0] = wxid;
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
            UtilLogs.saveLog("获取好友的微信号：" + wxid);
        }

        Boolean hasNoteNameObject = device.wait(Until.hasObject(By.res("com.tencent.mm", "u1")), 5000);
        if (hasNoteNameObject) {
            UiObject object = device.findObject(new UiSelector().resourceId("com.tencent.mm:id/u1"));
            String noteName = null;
            try {
                noteName = object.getText();
                result[1] = noteName;
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
            UtilLogs.saveLog("获取好友的备注名：" + noteName);
        }

        Boolean hasNickNameObject = device.wait(Until.hasObject(By.res("com.tencent.mm", "ax3")), 5000);
        if (hasNickNameObject) {
            UiObject object = device.findObject(new UiSelector().resourceId("com.tencent.mm:id/ax3"));
            String nickName = null;
            try {
                nickName = object.getText();
                result[2] = nickName;
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
            }
            UtilLogs.saveLog("获取好友的昵称：" + nickName);
        }

        return result;
    }

    /**
     * 查找列表中对方的头像，点击进入详细资料界面，获取其微信号等<br/>
     * 返回上一个界面-聊天界面
     *
     * @param title 好友自己的原始备注名
     * @return 返回资料数组：0-微信号，1-备注名，2-昵称
     */
    private String[] getFriendAvatar(String title) {
        UtilLogs.saveLog("查找好友的头像：" + title);

        String[] friendDetails = new String[3];
        friendDetails[0] = "";
        friendDetails[1] = "";
        friendDetails[2] = "";

        UiScrollable listViewObject = new UiScrollable(new UiSelector().className("android.widget.ListView"));

        boolean hasFriendAvatarObject = false;
        UiObject avatarObject = device.findObject(new UiSelector().description(title + "头像")); // 根据描述
        try {
            hasFriendAvatarObject = listViewObject.scrollIntoView(avatarObject);
            UtilLogs.saveLog("查找好友的头像-结果：" + hasFriendAvatarObject);
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        }
        listViewObject.waitForExists(5000);

        if (hasFriendAvatarObject) {
            UiObject2 avatarObject2 = device.findObject(By.descContains(title + "头像"));
            UtilLogs.saveLog("查找好友的头像-avatarObject2：" + avatarObject2);
            while (!avatarObject2.isClickable()) {
                avatarObject2 = avatarObject2.getParent();
            }
            avatarObject2.click();

            // nextAty，朋友详细信息界面

            TestUtilCtrl.showCurrentActivity(device, "是否为'详细资料'");

            friendDetails = getFriendDetails(1);


        } else { // 有时上面找不到
            List<UiObject2> objects = device.findObjects(By.descContains(title + "头像"));
            UtilLogs.saveLog("上面找不到，再次查找好友的头像-avatar");
            if (objects.size() > 0) {
                hasFriendAvatarObject = true;
                UiObject2 uiObject2 = objects.get(0);
                UtilLogs.saveLog("再次查找好友的头像-avatarObject2----：" + uiObject2);
                while (!uiObject2.isClickable()) {
                    uiObject2 = uiObject2.getParent();
                }
                uiObject2.click();

                // nextAty，朋友详细信息界面

                TestUtilCtrl.showCurrentActivity(device, "是否为'详细资料'");

                friendDetails = getFriendDetails(1);

            }
        }

        if (hasFriendAvatarObject) {
            UtilLogs.saveLog("最终找到好友的头像-avatar，并拿到了details");
            device.pressBack();
        }

        return friendDetails;
    }

    /**
     * 点击"通讯录"顶部的"新的朋友"选项，进入查找好友或者查看陌生人的好友请求
     */
    private void scrollGotoShowNewFriendBtn() {
        device.wait(Until.hasObject(By.res("com.tencent.mm", "lm")), 5000);

        UiObject2 lm = device.findObject(By.res("com.tencent.mm", "lm"));// 右边的字母快捷操作条
        Rect rect = lm.getVisibleBounds();
        int clickX = rect.centerX();
        int clickY = rect.top + 10;   // 向上箭头的位置
        device.click(clickX, clickY); // 点击回到ListView的顶端

        Boolean hasNewFriendObject = device.wait(Until.hasObject(By.textContains("新的朋友")), 5000);
        if (hasNewFriendObject) {

            device.wait(Until.hasObject(By.textContains("新的朋友")), 5000);

            UiObject2 object = device.findObject(By.textContains("新的朋友"));
            object.click();
            UtilLogs.saveLog("点击了-新的朋友");
        } else { ////////////////////////////////////// 如有有主动的好友请求，这里关键字会被遮挡
            // com.tencent.mm:id/bm6
            Boolean hasBm6Object = device.wait(Until.hasObject(By.res("com.tencent.mm", "bm6")), 5000);
            UtilLogs.saveLog("是否有新到好友请求：" + hasBm6Object);
            if (hasBm6Object) {
                UiObject2 object = device.findObject(By.res("com.tencent.mm", "bm6"));
                object.click();
                UtilLogs.saveLog("点击了-新朋友请求");
            } else {
                //[28,144][672,248]
                int x = (672 - 28) / 2;
                int y = (248 - 144) / 2;
                device.click(x, y);
                UtilLogs.saveLog("点击了-坐标x：" + x + "y：" + y);
            }
        }
    }
}
